<template>
  <a-row style="padding-bottom: 3%">
    <div>
      <a-col>
        <a-tag color="red"> {{ topicname }} [{{ totalCount }}]</a-tag>
      </a-col>
    </div>
    <div>
      <a-col>
        <a-tag color="red"> {{ topic }}</a-tag>
      </a-col>
    </div>
    <div style="padding-left: 3%">
      <a-tag color="green"> 定时刷新</a-tag>
    </div>
    <div>
      <a-switch
        v-model:checked="checked3"
        checked-children="开"
        un-checked-children="关"
      />
    </div>
    <div style="padding-left: 3%">
      <a-col>
        <a-space>
          <a-button type="primary" @click="leftDrawer = true">
            <ClockCircleTwoTone />
          </a-button>
        </a-space>
      </a-col>
    </div>
    <div style="padding-left: 3%">
      <a-col>
        <a-input-search
          v-model:value="searchValue"
          placeholder="筛选value"
          style="width: 200px"
          @search="onSearch"
        />
      </a-col>
    </div>

    <div style="padding-left: 3%; padding-top: 0.3%">
      <a-tag color="red"> 数量</a-tag>
    </div>
    <div>
      <a-input-number
        v-model:value="topicNum"
        :min="1"
        :max="10000"
        :step="10"
      />
    </div>

    <div style="padding-left: 3%">
      <a-col>
        <a-space>
          <a-button type="primary" @click="GeTtopicData">
            <ReloadOutlined />
          </a-button>
        </a-space>
      </a-col>
    </div>

    <div style="padding-left: 3%">
      <a-select
        ref="select"
        v-model:value="selval"
        style="width: 120px"
        @focus="focus"
        @change="handleChange"
      >
        <a-select-option value="partition">partition</a-select-option>
        <a-select-option value="offset">offset</a-select-option>
        <a-select-option value="key">key</a-select-option>
        <a-select-option value="value">value</a-select-option>
        <a-select-option value="timestamp">timestamp</a-select-option>
      </a-select>
    </div>
    <div style="padding-left: 1%; padding-top: 0.3%">
      <a-switch
        v-model:checked="selswi"
        checked-children="降序"
        un-checked-children="升序"
      />
    </div>
  </a-row>

  <el-table
    :data="pagedData"
    :default-sort="{ prop: 'timestamp', order: 'descending' }"
    style="width: 100%; height: 70vh"
  >
    <el-table-column label="序号" width="65">
      <template v-slot:default="scope">
        <a-tag :title="text"> {{ scope.$index + 1 }}</a-tag>
      </template>
    </el-table-column>
    <el-table-column prop="partition" label="partition" width="120">
      <template v-slot:default="scope">
        <a-tag color="green" :title="text">{{ scope.row.partition }}</a-tag>
      </template>
    </el-table-column>
    <el-table-column prop="offset" label="offset" width="120">
      <template v-slot:default="scope">
        <a-tag color="blue" :title="text">{{ scope.row.offset }}</a-tag>
      </template>
    </el-table-column>
    <el-table-column prop="key" label="key" width="120">
      <template v-slot:default="scope">
        <a-tooltip :title="scope.row.key">
          <a-tag color="red" :title="text">{{ scope.row.key }} </a-tag>
        </a-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="value" label="value">
      <template v-slot:default="scope">
        <a-tooltip :title="scope.row.value" color="purple">
          <a-tag
            @click="handlein(scope.row)"
            color="green"
            :style="{
              width: '38vw',
              overflow: 'hidden',
            }"
            :title="text"
            >{{ scope.row.value }}
          </a-tag>
        </a-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="timestamp" label="timestamp" width="180">
      <template v-slot:default="scope">
        <a-tag color="blue" :title="text">{{ scope.row.timestamp }}</a-tag>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    layout="total, sizes, prev, pager, next, jumper"
    :current-page="currentPage"
    :page-sizes="[10, 20, 50, 100]"
    :page-size="pageSize"
    :total="data.length"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="padding-top: 2%"
  />

  <a-spin v-if="loading" size="large" />
  <!-- 模态框 -->
  <a-modal
    v-model:open="Modalopen"
    :title="modelID"
    width="80%"
    wrap-class-name="full-modal"
    @ok="handleout"
  >
    <div class="scrollable-div">
      <json-viewer :value="jsonData" copyable boxed sort></json-viewer>
      <div style="padding-bottom: 10%">
        <div class="splide">
          <a-spin v-if="loadingModel" size="large" class="spin" />
        </div>
      </div>
    </div>
    <a-button type="primary" @click="exportData">导出JSON文件</a-button>
  </a-modal>

  <!-- 左侧态框 -->

  <a-drawer
    title="任务列表"
    :placement="placement"
    :closable="false"
    :open="leftDrawer"
    @close="onClose"
    :width="450"
  >
    <a-list :data-source="taskdata">
      <template #renderItem="{ item, index }">
        <a-list-item>
          <a-tag>{{ index + 1 }}</a-tag>
          <a-tag color="green">时间: {{ item.datetime }}</a-tag>
          <a-tag color="pink">数量: {{ item.topic_num }}</a-tag>
          <a-tag color="orange">进行中</a-tag>
        </a-list-item>
      </template>
    </a-list>
  </a-drawer>
</template>

<script>
import axios from "axios";
import { useRoute } from "vue-router";
import { ReloadOutlined, ClockCircleTwoTone } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";

export default {
  components: {
    ReloadOutlined,
    ClockCircleTwoTone,
  },
  data() {
    return {
      modelID: "",
      currentPage: 1,
      selval: "timestamp",
      selswi: true,
      pageSize: 10,
      subTitle: "",
      placement: "left",
      leftDrawer: false,
      jsonproData: { name: "John", age: 30, city: "New York" },
      Modalopen: false,
      startIndex: 0,
      jsonData: [],
      topicNum: 10,
      data: [],
      sortOrder: null,
      sortField: null,
      loading: false,
      loadingModel: false,
      checked3: false,
      route: useRoute().params.itemName,
      sortedData: [], // 排序后的数组
      topic: "",
      servers: "",
      searchValue: "",
      taskdata: [],
      topicname: "",
    };
  },
  methods: {
    exportData() {
      const jsonDataStr = JSON.stringify(this.jsonData, null, 2);
      const fileName = this.modelID + ".json";

      const blob = new Blob([jsonDataStr], {
        type: "application/json;charset=utf-8",
      });
      const link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.download = fileName;

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    isJSON(str) {
      const initText = str;
      if (typeof str == "string") {
        try {
          var obj = JSON.parse(str);
          if (typeof obj == "object" && obj) {
            this.jsonData = obj;
            return true;
          } else {
            this.jsonData = {
              文本: initText,
            };
            return false;
          }
        } catch (e) {
          try {
            str = str.replace(/\\"/g, '"');
            str = str.replace(/"{/g, "{");
            str = str.replace(/}"/g, "}");
            str = str.replace(/\\/g, "");
            const obj = JSON.parse(str);
            if (typeof obj == "object" && obj) {
              this.jsonData = obj;
              return true;
            } else {
              this.jsonData = {
                文本: initText,
              };
              return false;
            }
          } catch {
            console.log("error：" + str + "!!!" + e);
            this.jsonData = {
              文本: initText,
            };
            return false;
          }
        }
      } else {
        const initText = String(str);
        this.jsonData = {
          文本: initText,
        };
      }
    },
    handlein(recode) {
      this.jsonData = [];
      this.loadingModel = true;
      this.Modalopen = true;
      this.modelID = recode.id;
      axios
        .post("/api/topic/data/model", {
          id: recode.id,
        })
        .then((response) => {
          const value = response.data.data.value;
          this.isJSON(value);
          this.loadingModel = false;
        });
    },
    handleout() {
      this.Modalopen = false;
    },
    GeTtopicData() {
      axios.post("/api/topic/data/task", {
        topic: this.topic,
        servers: this.servers,
        topic_num: this.topicNum,
      });
      this.TopicData();
    },
    topicTask() {
      axios.post("/api/topic/data/task", {
        topic: this.topic,
        servers: this.servers,
        topic_num: this.topicNum,
      });
    },
    TopicData() {
      console.log(this.selval);
      console.log(this.selswi);
      this.loading = true; // 开始加载，显示 loading 效果
      axios
        .post("/api/topic/data", {
          topic: this.topic,
          servers: this.servers,
          topic_num: this.topicNum,
          key: this.selval,
          sort: this.selswi,
        })
        .then((response) => {
          this.data = response.data.data;
          this.loading = false; // 数据加载完成，隐藏 loading 效果
        })
        .catch((error) => {
          console.log(error.response.data.msg);
          this.loading = false; // 数据加载出错，隐藏 loading 效果
        });
    },
    startTimer() {
      this.timer = setInterval(() => {
        // 定时器逻辑
        if (this.searchValue) {
          this.onSearch();
        } else {
          this.GeTtopicData();
        }
      }, 5000);
    },
    stopTimer() {
      clearInterval(this.timer); // 关闭定时器
    },
    onSearch() {
      this.loading = true; // 开始加载，显示 loading 效果
      if (this.searchValue.trim() === "") {
        this.GeTtopicData();
      } else {
        this.topicTask();
        axios
          .post("/api/topic/data/search", {
            topic: this.topic,
            servers: this.servers,
            searchKey: this.searchValue,
            key: this.selval,
            sort: this.selswi,
            topic_num: this.topicNum,
          })
          .then((response) => {
            this.data = response.data.data;
            this.loading = false; // 数据加载完成，隐藏 loading 效果
          })
          .catch((error) => {
            console.log(error.response.data.msg);
            this.loading = false; // 数据加载出错，隐藏 loading 效果
          });
      }
    },
    stopTask() {
      // 关闭定时器
      clearInterval(this.tasktimer);
      this.leftDrawer = false;
    },
    startTask() {
      this.tasktimer = setInterval(() => {
        // 定时器逻辑
        axios
          .post("/api/topic/task", {
            topic: this.topic,
            servers: this.servers,
          })
          .then((response) => {
            this.taskdata = response.data.data;
            const tasklen = this.taskdata.length;
            if (tasklen > 0) {
              message.info(
                "任务正在执行, 当前执行任务数:" + this.taskdata.length + "个"
              );
            }
          });
      }, 3000);
    },
    GeTtask() {
      this.startTask();
    },
    onClose() {
      // this.stopTask();
      this.leftDrawer = false;
    },
  },
  watch: {
    checked3(value) {
      if (value) {
        // 当开关打开时，启动定时器
        this.startTimer();
      } else {
        // 当开关关闭时，关闭定时器
        this.stopTimer();
      }
    },
  },
  created() {
    const params = decodeURIComponent(this.route).split("|||");
    console.log(params);
    this.topic = params[0];
    this.servers = params[1];
    this.topicname = params[2];
    this.GeTtopicData();
    this.startTask();
  },
  computed: {
    totalCount() {
      return this.data.length;
    },
    pagedData() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.data.slice(startIndex, endIndex);
    },
  },
  beforeUnmount() {
    // 在页面退出之前关闭定时器
    clearInterval(this.timer);
    clearInterval(this.tasktimer);
  },
  onSearch() {
    console.log(this.searchValue);
    if (this.searchValue.trim() === "") {
      // 如果搜索关键字为空，则显示全部数据
      this.GeTtopicList();
    } else {
      // 使用筛选条件过滤数据
      const regex = new RegExp(this.searchValue, "i");
      this.data = this.data.filter((item) => {
        console.log(item);
        return regex.test(item.value);
      });
    }
  },
};
</script>
<style>
.column-content {
  max-width: 40vw;

  /* 设置最大宽度 */
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsi50;
}

.scrollable-div {
  overflow-y: auto;
  height: 60vh; /* 设置高度为适当的值 */
}

.splide {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
